﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ef;
using Entity;

namespace ef_CodeFirst.Controllers
{
    [HandleError]
    public class HomeController : BaseController
    {
        ef.ServiceInterface.IUserService iUserService = null;
        public HomeController()
        {
            iUserService = new ef.ServiceImplement.UserService();
        }

        public ActionResult Index(int? page)
        {
            vp = new VCommons.Entity.VPredication();
            pp = new VCommons.Entity.PagingParam(page ?? 1, 10);
            return View(iUserService.GetUser(vp, pp));
        }
        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(FormCollection form)
        {

            UserBase_Ext entity = new UserBase_Ext();
            TryUpdateModel(entity);
            if (ModelState.IsValid)
            {
                iUserService.RegisterUser(entity);
            }
            return View();
        }

        public ActionResult Edit(int? id)
        {
            if (!id.HasValue)
                return RedirectToAction("Index");
            UserBase_Ext entity = iUserService.GetUserByID(id.Value);
            return View(entity);
        }
        [HttpPost]
        public ActionResult Edit(FormCollection form)
        {
            int _id;
            int.TryParse(form["ID"], out _id);
            UserBase_Ext entity = iUserService.GetUserByID(_id);
            TryUpdateModel(entity);
            if (ModelState.IsValid)
            {
                iUserService.EditUser(entity);
            }
            return RedirectToAction("Index");
        }

        public ActionResult Delete(int? id)
        {
            if (!id.HasValue)
                return RedirectToAction("Index");
            try
            {
                iUserService.DelUser(id.Value);
                return Json(new { res = true });
            }
            catch (Exception)
            {
                return Json(new { res = false });
            }
        }

        public ActionResult About()
        {
            return View();
        }
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult EnsForJS(string str)
        {
            return Content(VCommons.Utils.UrlEncode(VCommons.Security.DES.EncryptDES(str)));
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult DesForJS(string str)
        {
            return Content(VCommons.Security.DES.DecryptDES(VCommons.Utils.UrlDecode(str)));
        }
    }
}
